#!/bin/bash

set -e

# Target directory
TARGET_DIR=$(dirname "$(pwd)")
echo "builder target dir: ${TARGET_DIR}"
# RootFS directory
ROOTFS_DIR="${TARGET_DIR}/sys_rootfs"

echo "Chroot Start Basic Config..."
# Chroot configure
chroot "$ROOTFS_DIR" /bin/bash <<EOF
# install basic packages
echo "install basic packages..."
apt update
apt install -y vim git

# configure root password
echo "configure root password..."
echo 'root:root' | chpasswd

# configure develop password
echo 'develop:develop' | chpasswd

# configure hostname
echo "configure hostname..."
cat > /etc/hostname <<HOSTNAME
DevServer
HOSTNAME

# configure network
echo "configure network..."
cat > /etc/network/interfaces <<NETWORK
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
address 192.168.100.100
netmask 255.255.255.0
gateway 192.168.100.254
NETWORK

# configure DNS
echo "configure DNS..."
cat > /etc/resolv.conf <<RESOLV
nameserver 192.168.100.1
search localdomain
RESOLV

# remove unnecessary packages
echo "remove unnecessary packages..."
apt autoremove -y
apt clean
# clean cache
echo "clean cache..."
rm -rf /var/cache/*
rm -rf /var/lib/apt/lists/*
# clean temporary files
echo "clean temporary files..."
rm -rf /tmp/*
rm -rf /var/tmp/*  
# clean log files
echo "clean log files..."
find /var/log -type f -name "*.log" -exec rm -f {} \;
find /var/log -type f -name "*.gz" -exec rm -f {} \;
EOF

echo "Chroot Finish Basic Config..."
